package com.ysd.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.extension.service.additional.query.impl.QueryChainWrapper;
import com.fasterxml.jackson.databind.ser.BeanPropertyFilter;
import com.ysd.common.es.SkuEsModel;
import com.ysd.common.utils.R;
import com.ysd.gulimall.product.entity.*;
import com.ysd.gulimall.product.feign.SearchFeignService;
import com.ysd.gulimall.product.service.*;
import com.ysd.gulimall.product.vo.spusave.BaseAttrs;
import com.ysd.gulimall.product.vo.spusave.Images;
import com.ysd.gulimall.product.vo.spusave.Skus;
import com.ysd.gulimall.product.vo.spusave.SpuSaveVo;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ysd.common.utils.PageUtils;
import com.ysd.common.utils.Query;

import com.ysd.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    SpuInfoDescService spuInfoDescService;

    @Autowired
    SpuImagesService spuImagesService;

    @Autowired
    ProductAttrValueService productAttrValueService;

    @Autowired
    SkuInfoService skuInfoService;
    @Autowired
    SkuImagesService skuImagesService;
    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    private BrandService brandService;
    @Autowired
    CategoryService categoryService;

    @Autowired
    private SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<SpuInfoEntity>();
//        status: publish_status
//        key:
//        brandId: 12
//        catelogId: 225


        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and(w -> {
                w.eq("id", key).or().like("spu_name", key);
            });
        }

        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)) {
            wrapper.eq("publish_status", status);
        }

        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId)) {
            wrapper.eq("brand_id", brandId);
        }
        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId)) {
            wrapper.eq("catalog_id", catelogId);
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    //@Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo spuSaveVo) {
        //1,保存基本信息
        SpuInfoEntity infoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVo, infoEntity);
        infoEntity.setCreateTime(new Date());
        infoEntity.setUpdateTime(new Date());
        this.save(infoEntity);

        System.out.println("infoEntity" + infoEntity);


        //2, 保存spu的描述
        SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
        descEntity.setSpuId(infoEntity.getId());
        descEntity.setDecript(Strings.join(spuSaveVo.getDecript(), ','));

        spuInfoDescService.save(descEntity);
        //3，保存图片信息
        List<String> images = spuSaveVo.getImages();
        spuImagesService.saveImages(infoEntity.getId(), images);

        SpuImagesEntity imagesEntity = new SpuImagesEntity();

        //4，保存spu规格

        List<BaseAttrs> baseAttrs = spuSaveVo.getBaseAttrs();
        List<ProductAttrValueEntity> list = baseAttrs.stream().map(baseAttr -> {
            ProductAttrValueEntity valueEntity = new ProductAttrValueEntity();
            BeanUtils.copyProperties(baseAttr, valueEntity);
            valueEntity.setSpuId(infoEntity.getId());
            return valueEntity;
        }).collect(Collectors.toList());

        productAttrValueService.saveBatch(list);

        //5，保存sku信息


        List<Skus> skus = spuSaveVo.getSkus();

        //5.1 保存sku基本信息
        //5.2会员
        //todo

        //5.3 图片


        //5.4销售属性
        skus.stream().map(sku -> {

            SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
            BeanUtils.copyProperties(sku, skuInfoEntity);
            skuInfoEntity.setSpuId(infoEntity.getId());
            //设置默认图片
            for (Images image : sku.getImages()) {
                if (image.getDefaultImg() == 1) {
                    skuInfoEntity.setSkuDefaultImg(image.getImgUrl());
                }
            }

            skuInfoService.save(skuInfoEntity);
            //5.3 图片

            List<SkuImagesEntity> skuImagesEntities = sku.getImages().stream().map(image -> {
                SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                BeanUtils.copyProperties(image, skuImagesEntity);
                return skuImagesEntity;
            }).collect(Collectors.toList());

            skuImagesService.saveBatch(skuImagesEntities);


            //销售属性

            List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = sku.getAttr().stream().map(attr -> {
                SkuSaleAttrValueEntity saleAttrValueEntity = new SkuSaleAttrValueEntity();
                BeanUtils.copyProperties(attr, saleAttrValueEntity);
                saleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());
                return saleAttrValueEntity;
            }).collect(Collectors.toList());

            skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);
            return skuInfoEntity;
        }).collect(Collectors.toList());


    }

    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {

        //先查询sku表里的数据
        SkuInfoEntity skuInfoEntity = skuInfoService.getById(skuId);

        //获得spuId
        Long spuId = skuInfoEntity.getSpuId();

        //再通过spuId查询spuInfo信息表里的数据
        SpuInfoEntity spuInfoEntity = this.baseMapper.selectById(spuId);

        //查询品牌表的数据获取品牌名
        BrandEntity brandEntity = brandService.getById(spuInfoEntity.getBrandId());
        if (brandEntity != null && brandEntity.getBrandId() != null) {
            spuInfoEntity.setBrandId(brandEntity.getBrandId());
        }


        return spuInfoEntity;
    }

    @Override
    public SpuInfoEntity up(Long spuId) {

        SpuInfoEntity entity = this.getBaseMapper().selectById(spuId);
        entity.setPublishStatus(1);
        this.updateById(entity);

        //1、查出当前spuId对应的所有sku信息,品牌的名字
        List<SkuInfoEntity> skuInfoEntities = (List<SkuInfoEntity> )skuInfoService.getSkusBySpuId(null,spuId).getList();

        //2、封装每个sku的信息
        List<SkuEsModel> collect = skuInfoEntities.stream().map(sku -> {
            //组装需要的数据
            SkuEsModel esModel = new SkuEsModel();
            esModel.setSkuTitle(sku.getSkuTitle());
            esModel.setSkuId(sku.getSkuId());

            return esModel;
        }).collect(Collectors.toList());

        //TODO 5、将数据发给es进行保存：gulimall-search
        R r = searchFeignService.productStatusUp(collect);


        return null;
    }
}